package org.example.servlet;

import org.example.model.Product;
import org.example.service.ProductService;
import org.example.service.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/category")
public class CategoryProductsServlet extends HttpServlet {
    private ProductService productService;
    
    @Override
    public void init() throws ServletException {
        productService = new ProductServiceImpl();
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            int categoryId = Integer.parseInt(request.getParameter("id"));
            
            // 添加调试信息
            System.out.println("请求的分类ID: " + categoryId);
            
            // 获取分类商品
            List<Product> products = productService.getProductsByCategory(categoryId);
            
            // 打印获取到的商品数量
            System.out.println("获取到的商品数量: " + (products != null ? products.size() : 0));
            if (products != null && !products.isEmpty()) {
                System.out.println("第一个商品: " + products.get(0).getName());
            }
            
            // 设置分类名称
            String categoryName = "";
            switch(categoryId) {
                case 1: categoryName = "手机数码"; break;
                case 2: categoryName = "服装服饰"; break;
                case 3: categoryName = "电脑办公"; break;
                case 4: categoryName = "家居家装"; break;
                case 5: categoryName = "食品生鲜"; break;
                default: categoryName = "全部商品";
            }
            
            request.setAttribute("products", products);
            request.setAttribute("currentCategory", categoryId);
            request.setAttribute("categoryName", categoryName);
            request.getRequestDispatcher("/taolele-mall.jsp").forward(request, response);
        } catch (NumberFormatException e) {
            System.out.println("分类ID解析错误");
            response.sendRedirect(request.getContextPath() + "/taolele-mall.jsp");
        } catch (Exception e) {
            System.out.println("发生错误: " + e.getMessage());
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/taolele-mall.jsp");
        }
    }
} 